<?php

/**
 *
 */
class Admin_Model_Mapper_Auth extends App_Model_Mapper_Abstract
{
	/**
	 * Autentica usuario no painel administrador
	 * 
	 * @access public
	 * @return boolean
	 */
	public function login ()
	{		
		$valid = false;
		
		try {
			
			$adapter = new Zend_Auth_Adapter_DbTable(
				Zend_Db_Table_Abstract::getDefaultAdapter(),
				'usuario',
				'user_email',
				'user_senha',
				'SHA1(?)'
			);
			
			$adapter->setIdentity( $this->_data['email'] );
			$adapter->setCredential( $this->_data['senha'] );
			
			$adapter->getDbSelect()->where( 'user_status = ?', 1 );
			
			$auth = Zend_Auth::getInstance();
			
			$result = $auth->authenticate( $adapter );
			
			if ( $result->isValid() ) {

				$row = $adapter->getResultRowObject( null, 'user_senha' );
				
				$auth->getStorage()->write( $row );
				
				$this->_lastAccess();
				$this->_createCookie();
				
				$valid = true;
				
			} else throw new Exception('Login is not valid');
			
		} catch ( Exception $e ) {
			
			$auth->getStorage()->clear();
			$auth->clearIdentity();
			
		}
		
		return $valid;
	}
	
	/**
	 * Cria cookie para que o usuario permaneca logado 
	 * 
	 * @access protected
	 * @return void
	 */
	protected function _createCookie ()
	{
		//Nome do cookie
		$name = 'auth_admin_' . $this->_config->geral->appid;
		
		if ( !empty($this->_data['keep-logged']) ) {
			
    		$data 	= array( 'user_hash' => md5(uniqid(time())) );
			$where 	= array( 'user_id = ?' => Zend_Auth::getInstance()->getIdentity()->user_id );
	
			$dbUsuario = App_Model_DbTable_Factory::get( 'Usuario' );
			
			$dbUsuario->update( $data, $where );

    		//Expira em 30 dias
    		setcookie( $name, $data['user_hash'], (time() + 60 * 60 * 24 * 30), '/' );
			
		} else {
			
			setcookie( $name, false, time(), '/' );
			
		}
	}

	/**
	 * Busca dados de acordo com hash do cookie
	 *
	 * @access public
	 * @param string $cookie
	 * @return App_Model_DbTable_Row_Abstract
	 */
	public function fetchRowCookie ( $cookie )
	{
		$dbUsuario = App_Model_DbTable_Factory::get( 'Usuario' );
		
		$where = array(
			'user_hash = ?' 	=> $cookie,
			'user_status = ?' 	=> 1
		);
		
		$row = $dbUsuario->fetchRow( $where );
	}
	
	/**
	 * Atualiza os dados referentes ao ultimo acesso do usuario
	 * 
	 * @access protected
	 * @return void
	 */
	protected function _lastAccess ()
	{
		$data = array(
			'user_iplogin' => $_SERVER['REMOTE_ADDR'],
			'user_dtlogin' => Zend_Date::now()->toString('yyyy-MM-dd HH:mm:ss') 
		);
		
		$auth = Zend_Auth::getInstance();
		
		$where = array( 'user_id = ?' => $auth->getIdentity()->user_id );

		$dbUsuario = App_Model_DbTable_Factory::get( 'Usuario' );
		
		$dbUsuario->update( $data, $where );
	}
}
